package tankattack.sprites;

import gamepack.*;
import java.util.Vector;

/** @author Somanath
*/

/*
/**  CompileTime class Dependency - None
 *   Runtime class Dependency     - None
 *   RunTime interface Requirements - None
 *   #Does: On collision, invokes owner.handleCollision(bullet,collider)
*/
public class Bullet extends Sprite {

    // Recomended: This is required if you want the resources to load during
    // class load itself. If you don't the resources will be read from xml
    // file when first object is created. This will feel slower...
    public static Resource r = ResourceLoader.getResource("tankattack.sprites.Bullet");
	public static String explosionSpawnStr = r.getValue("explosionSpawnStr").trim();
	int speed;
	
	 static {
		//System.out.println("#########################  Bullet.java Compiled ##########################");
     }

	//<Data name="spawnformat"> tankattack.sprites.Bullet #x=%d,y=%d,dir=%d,attributes[]=%s,colliders[]=%s # speed=%d"  </Data>	
	public Bullet() {	// x,y,dir,attributes,colliders,speed
		res = r;							                               // point to the Bullet resouces img/sound as per config file	
		speed = getArgs().getAsInt("speed"); //nteger.parseInt( Sprite.getArgs().strMap.get("speed").toString() );
		
		if( dir == EAST ) 			{ 	vx = speed; vy=0;		} 
		else if ( dir == WEST ) 	{	vx = -speed; vy=0;		} 
		else if ( dir == NORTH) 	{	vx=0;  vy=-speed;		} 
		else if ( dir == SOUTH) 	{	vx=0; vy=speed;			}
		
		setZOrder( r.getValueAsInt("zorder") );                              // retrieve from configuration file
		startSprite();
	}

	public void run() {
		if ( state == NORMAL ) {  
			normal();
		} else if ( state == DYING ) { //TODO: read spawn string from config
			//Sprite.spawn( String.format( explosionSpawnStr, x, y ) , this ); // crashing.. check this.
			setState(DEAD);
			
			String spawnString = "x="+x+",y="+y+",type=1";
			Sprite.getArgs().set(spawnString,null);
			Sprite.spawnClass("tankattack.sprites.Explosion",spawnString,this);			 							
		} else if ( state == DEAD ) {
			stopSprite();
		}	
	}

	public void normal() {
	    MotionResult mr = Motion.canMove( this, vx, vy );
	    if ( mr.canMove ) {
		
			Collidable c = Motion.move( this, mr.dx, mr.dy);
			
            Vector[] vecCol = (Vector[]) colliders;
            Vector vc = Collision.getCollisions( c, vecCol );
            for( int i=0;i<vc.size();i++) {
                 Sprite prey = (Sprite) vc.get(i);
                 if( prey != this )
                   handleCollision( prey );
            }
        }
		if( Room.isOutside(x,y) ) {	setState(DEAD); }
	}

	public void handleCollision(Sprite s) {
	    parent.handleCollision(this,s);
	}
}